package com.system.handler;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Component;

import com.system.comm.utils.FrameJsonUtil;
import com.system.comm.utils.FrameSpringBeanUtil;

/**
 * 业务处理类
 * @author yuejing
 * @date 2016年1月29日 下午4:24:53
 * @version V1.0.0
 */
@Component
public class Dispatcher {

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Object process(String uri, String body) throws Exception {
		String[] uriArr = uri.split("/");
		int uriLen = uriArr.length;
		//实体名称
		String beanName = uriArr[uriLen - 2];
		//处理的方法
		String beanMethodName = uriArr[uriLen - 1];
		/*if(FrameStringUtil.isNotEmpty(uriArr[0])) {
			beanName = uriArr[uriLen - 2];
			beanMethodName = uriArr[uriLen - 1];
		} else {
			beanName = uriArr[uriLen - 2];
			beanMethodName = uriArr[uriLen - 1];
		}*/
		BaseHandle handle = FrameSpringBeanUtil.getBean(beanName + "Handle");

		int methodIndex = beanMethodName.indexOf("?");
		if(methodIndex != -1) {
			beanMethodName = beanMethodName.substring(0, methodIndex);
		}

		Map<String, Object> params = FrameJsonUtil.toMap(body);
		if(params == null) {
			params = new HashMap<String, Object>();
		}
		
		Class clazz = handle.getClass();
		Method m = clazz.getMethod(beanMethodName, Map.class);
		Object object = m.invoke(handle, params);
		return object;
	}
}
